<template>
  <div class="info-form">
    <div class="info-form-top" ref="top">
      <template v-if="operation <= 1 || operation == 7">
        <el-row class="row">
          <el-col :span="16">
            <span>供应商：</span>
            <el-select 
              v-model="postParam.supplierId" 
              style="width: 120px"
              @change="onChangeSupplier"
              :class="{error: supplierError}"
            >
              <template v-for="item in suppliers">
                <el-option 
                  :key="item.id" 
                  :label="item.text" 
                  :value="item.id">
                </el-option>
              </template>
            </el-select>
            <span class="span-20">入库方式：</span>
            <el-select 
              v-model="postParam.wareHousingType" 
              style="width: 120px"
              :disabled="type == 1"
            >
              <template v-for="item in wareHousingTypes">
                <el-option 
                  :key="item.id" 
                  :label="item.text" 
                  :value="item.id"
                >
                </el-option>
              </template>
            </el-select>
            <template v-if="type == 0">
              <span class="span-20">支付状态：</span>
              <el-select 
                v-model="postParam.payStatus" 
                style="width: 120px"
              >
                <template v-for="item in payStatus">
                  <el-option 
                    :key="item.id" 
                    :label="item.text" 
                    :value="item.id"
                  >
                  </el-option>
                </template>
              </el-select>
            </template>
            <template v-if="type == 0">
              <span class="span-20">备注：</span>
              <el-input v-model="postParam.remark" placeholder="输入内容" style="width: 120px" />
            </template>
          </el-col>
          <el-col :span="8" class="button">
            <template v-if="!readOnly">
              <el-button @click="onUpdateBatchNo">批量修改批次号</el-button>
              <el-button @click="onUpdateTerm">批量修改有效期</el-button>
            </template>
          </el-col>
        </el-row>
      </template>
      <template v-else>
        <el-row class="row">
          <el-col :span="16">
            <table class="info-table">
              <tr>
                <td>供应商：{{postParam.supplierName || '无'}}</td>
                <td>
                  <span>入库方式：</span>
                  <housingType :wareHousingType="postParam.wareHousingType" />
                </td>
                <td v-if="type == 0 && operation != 3">
                  <span class="span-20">支付状态：</span>
                  <el-select 
                    v-model="postParam.payStatus" 
                    style="width: 120px"
                  >
                    <template v-for="item in payStatus">
                      <el-option 
                        :key="item.id" 
                        :label="item.text" 
                        :value="item.id"
                      >
                      </el-option>
                    </template>
                  </el-select>
                </td>
                <td v-if="operation == 4">退回理由：{{postParam.refundContent}}</td>
                <td v-if="operation == 2">
                  <span>退回理由：{{ postParam.refundContent }}</span>
                  <el-input v-model="refundContent" placeholder="退回理由" style="width: 120px" />
                </td>
                <!-- <td>
                  <span>订单状态：</span>
                  <housingStatus :value="postParam.status" />
                </td> -->
                <td v-if="type == 0">订单备注：{{postParam.remark}}</td>
              </tr>
            </table>
          </el-col>
          <el-col v-if="type == 0 && operation == 3" :span="8" class="button">
            <span class="span-20">支付状态：</span>
            <el-select 
              v-model="postParam.payStatus" 
              style="width: 120px"
            >
              <template v-for="item in payStatus">
                <el-option 
                  :key="item.id" 
                  :label="item.text" 
                  :value="item.id"
                >
                </el-option>
              </template>
            </el-select>
            <el-button
              @click="onSavePayStatus"
              style="margin-left: 10px"
              type="primary" plain
            >保存</el-button>
          </el-col>
        </el-row>
      </template>
    </div>
    <el-row class="info-form-tab" :style="tabStyle">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane
          :disabled="disabledTab"
          label="西药及中成药"
          name="7"
        >
          <infoFormTable
            :wareHousingType="postParam.wareHousingType"
            @onChangeTotalPrice="onChangeTotalPrice"
            :editRedPun="postParam.status != 3"
            :waitConfirm="waitConfirm"
            :showActual="showActual"
            @disabled="onDisabled"
            :readOnly="readOnly"
            :sactors="sactors"
            :drugType="7"
            :type="type"
            ref="table1"
          />
        </el-tab-pane>
        <el-tab-pane
          :disabled="disabledTab"
          label="中药饮片"
          name="1"
        >
          <infoFormTable
            :wareHousingType="postParam.wareHousingType"
            @onChangeTotalPrice="onChangeTotalPrice"
            :editRedPun="postParam.status != 3"
            :waitConfirm="waitConfirm"
            :showActual="showActual"
            @disabled="onDisabled"
            :readOnly="readOnly"
            :sactors="sactors"
            :drugType="1"
            :type="type"
            ref="table2"
          />
        </el-tab-pane>
        <el-tab-pane
          :disabled="disabledTab"
          label="颗粒剂"
          name="2"
        >
          <infoFormTable
            :wareHousingType="postParam.wareHousingType"
            @onChangeTotalPrice="onChangeTotalPrice"
            :editRedPun="postParam.status != 3"
            :waitConfirm="waitConfirm"
            :showActual="showActual"
            @disabled="onDisabled"
            :readOnly="readOnly"
            :sactors="sactors"
            :drugType="2"
            :type="type"
            ref="table3"
          />
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <el-dialog
      width="500px"
      append-to-body
      title="批量修改批次号"
      :close-on-click-modal="false"
      :visible.sync="dialog.showBatchNo"
    >
      <el-form label-width="80px" style="margin-right: 10px;">
        <el-form-item label="批次号:">
          <el-input v-model="dialog.batchNo" placeholder="请输入批次号" />
        </el-form-item>
      </el-form>
      <div class="dialog-footer" style="text-align: center">
        <el-button @click="dialog.showBatchNo=false">关闭</el-button>
        <el-button type="primary" @click="onSubmitBatchNo">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog
      width="500px"
      append-to-body
      title="批量修改有效期"
      :close-on-click-modal="false"
      :visible.sync="dialog.showBatchTerm"
    >
      <el-form label-width="80px" style="margin-left: 60px;">
        <el-form-item label="有效期:">
          <el-date-picker
            v-model="dialog.termOfValidity"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
          />
        </el-form-item>
      </el-form>
      <div class="dialog-footer" style="text-align: center">
        <el-button @click="dialog.showBatchTerm=false">关闭</el-button>
        <el-button type="primary" @click="onSubmitBatchTerm">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updatePayStatus, detail, getSuppliers } from "@/api/storageRoom/drugWareHousing";
import { getAll } from "@/api/system/conversionFactor";
import infoFormTable from "./infoFormTable";
import { parseTime, formatMoney } from "@/utils/index";
import housingType from "./housingType";
import { mapGetters } from "vuex";
import housingStatus from "./status";

export default {
  name: "infoForm",
  props: {
    readOnly: {
      type: Boolean,
      default: false // 默认可编辑
    },
    operation: {
      type: Number,
      default: 0
    },
    warehousingId: {
      type: Number,
      default: 0
    },
    // 0-入库, 1-采购计划
    type: {
      type: Number,
      default: 0
    }
  },
  components: { infoFormTable, housingType, housingStatus },
  computed: {
    ...mapGetters(["wareHousingTypes"]),
    waitConfirm() {
      return this.operation === 6;
    },
    showActual() {
      if(this.operation == 6 || this.operation == 3 || this.operation == 7) {
        return true;
      }
      return false;
    }
  },
  watch: {
    operation(val) {
      this._setTopHeight();
    }
  },
  data() {
    return {
      postParam: {
        checkTime: null,
        checkUserId: null,
        checkUserName: null,
        createTime: null,
        createUserId: null,
        createUserName: null,
        orderTotal: 0,
        pharmacyId: null,
        remark: null,
        status: 0,
        wareHousingNo: null,
        wareHousingType: 6,
        supplierId: null,
        supplierName: null,
        payStatus: 0,
        refundContent: null,
        warehousingQuantity: 0,
        drugType: null,
        warehousingTime: null,
        warehousingUserId: null,
        warehousingUserName: null,
      },
      dialog: {
        showBatchNo: false,
        showBatchTerm: false,
        termOfValidity: null,
        batchNo: null
      },
      pickerOptions: {
        disabledDate(d) {
          let time = new Date();
          return d.getTime() < time.getTime();
        }
      },
      payStatus: [
        { id: 0, text: "未付款" },
        { id: 1, text: "已付款" },
      ],
      tabStyle: {},
      activeName:'7',
      suppliers: [],
      sactors: [],
      validObj: {},
      supplierError: false,
      refundContent: null,
      disabledTab: false
    }
  },
  created() {
    this.$store.dispatch("GetInfo").then(res => {
      this.postParam.pharmacyId = res.pharmacyId;
      this._getSuppliers();
      this._getFactors();
    });
  },
  mounted() {
    this.initInfoPage();
    this._setTopHeight();
  },
  methods: {
    parseTime,
    formatMoney,
    handleClick() {
      this.selectDrugType = Number(this.activeName);
    },
    onUpdateBatchNo() {
      if(this._getList().length === 0) {
        this.$message.error("请选择需要修改的数据！");
        return;
      }
      this.dialog.showBatchNo = true;
    },
    onUpdateTerm() {
      if(this._getList().length === 0) {
        this.$message.error("请选择需要修改的数据！");
        return;
      }
      this.dialog.showBatchTerm = true;
    },
    onSubmitBatchNo() {
      let list = this._getList();
      list.forEach(item => {
        item.batchNo = this.dialog.batchNo;
      });
      this.$notify({
        title: "修改成功！",
        type: "success"
      });
      this.dialog.showBatchNo = false;
      this.dialog.batchNo = null;
    },
    onSubmitBatchTerm() {
      let list = this._getList();
      list.forEach(item => {
        item.termOfValidity = this.dialog.termOfValidity;
      });
      this.$notify({
        title: "修改成功！",
        type: "success"
      });
      this.dialog.showBatchTerm = false;
      this.dialog.termOfValidity = null;
    },
    initInfoPage() {
      this._operationInit();
      if(this.warehousingId) {
        this._searchDetail();
      }
    },
    getPostParam() {
      let drugType = Number(this.activeName);
      let postParam = {
        ...this.postParam
      };
      let list = this._getList();
      postParam.list = list;
      postParam.warehousingQuantity = list.length;
      postParam.drugType = drugType;
      return postParam;
    },
    onChangeSupplier(supplierId) {
      let suppliers = this.suppliers.filter(item => {
        return item.id === supplierId;
      });

      this.supplierError = false;
      this.postParam.supplierId = supplierId;
      this.postParam.supplierName = suppliers[0].text;
    },
    onChangeTotalPrice() {
      let totalPrice = 0;
      let list = this._getList();
      list.forEach(item => {
        totalPrice += item.commodityPrice;
      });
      this.$emit("onChangeTotalPrice", totalPrice);
    },
    validator(call) {
      this.validObj.count = 0;
      this.validObj.backCall = call;
      this.validObj.errors = [];
      // 赠品入库，盘点入库，供应商非必填
      if(!this.postParam.supplierId && this.postParam.wareHousingType != 5 && this.postParam.wareHousingType != 7) {
        this.supplierError = true;
        this.validObj.errors.push("请选择供应商！");
      }
      
      this.$refs.table1.validator((errors, fileds) => {
        this._validFun(errors, fileds);
      });
      this.$refs.table2.validator((errors, fileds) => {
        this._validFun(errors, fileds);
      });
      this.$refs.table3.validator((errors, fileds) => {
        this._validFun(errors, fileds);
      });
    },
    onSavePayStatus() {
      // 保存支付状态
      let data = this.getPostParam();
      let param = {
        id: data.id,
        payStatus: data.payStatus
      };
      updatePayStatus(param).then(() => {
        this.$notify({
          title: "保存成功！",
          type: "success"
        });
        this.$emit("success", true);
      });
    },
    // 禁用/启用tab
    onDisabled(val) {
      this.disabledTab = val;
    },
    _validFun(errors, fileds) {
      this.validObj.count ++;
      if(errors) {
        this.validObj.errors.push(fileds);
      }
      if(this.validObj.count === 3) {
        this.validObj.backCall(this.validObj.errors.length > 0, this.validObj.errors);
      }
    },
    _operationInit() {
      this.postParam.checkTime = null;
      this.postParam.checkUserId = null;
      this.postParam.checkUserName = null;
      this.postParam.createTime = null;
      this.postParam.createUserId = null;
      this.postParam.createUserName = null;
      this.postParam.orderTotal = 0;
      this.postParam.pharmacyId = this.pharmacyId;
      this.postParam.remark = null;
      this.postParam.status = 0;
      this.postParam.wareHousingNo = null;
      this.postParam.wareHousingType = 6;
      this.postParam.payStatus = 0;
      this.postParam.refundContent = null;
      this.postParam.warehousingQuantity = 0;
      this.postParam.drugType = null;
      this.postParam.warehousingTime = null;
      this.postParam.warehousingUserId = null;
      this.postParam.warehousingUserName = null;
      this.refundContent = null;

      if(this.type == 1) {
        // 采购时入库类型默认平台采购
        this.postParam.wareHousingType = 1;
      }
      switch(this.operation) {
        case 0:
        case 1:
        case 4:
          this.$refs.table1.setTableList([{search: true}]);
          this.$refs.table2.setTableList([{search: true}]);
          this.$refs.table3.setTableList([{search: true}]);
          break;
        default:
          this.$refs.table1.setTableList([]);
          this.$refs.table2.setTableList([]);
          this.$refs.table3.setTableList([]);
          break;
      }
      // if(this.$refs.table) {
      //   this.$refs.table.clearSelection();
      // }
    },
    _searchDetail() {
      detail(this.warehousingId).then(res => {
        this.operation = res.status;
        this._drugDistribute(res.list);
        this.$set(this.postParam, "checkTime", res.checkTime);
        this.$set(this.postParam, "checkUserId", res.checkUserId);
        this.$set(this.postParam, "checkUserName", res.checkUserName);
        this.$set(this.postParam, "createTime", res.createTime);
        this.$set(this.postParam, "createUserId", res.createUserId);
        this.$set(this.postParam, "createUserName", res.createUserName);
        this.$set(this.postParam, "orderTotal", res.orderTotal);
        this.$set(this.postParam, "pharmacyId", res.pharmacyId);
        this.$set(this.postParam, "remark", res.remark);
        this.$set(this.postParam, "status", res.status);
        this.$set(this.postParam, "wareHousingNo", res.wareHousingNo);
        this.$set(this.postParam, "wareHousingType", res.wareHousingType);
        this.$set(this.postParam, "id", res.id);
        this.$set(this.postParam, "supplierId", res.supplierId);
        this.$set(this.postParam, "supplierName", res.supplierName);
        this.$set(this.postParam, "storeName", res.storeName);
        this.$set(this.postParam, "payStatus", res.payStatus);
        this.$set(this.postParam, "refundContent", res.refundContent);
        this.$set(this.postParam, "warehousingQuantity", res.warehousingQuantity);
        this.$set(this.postParam, "drugType", res.drugType);
        this.$set(this.postParam, "warehousingTime", res.warehousingTime);
        this.$set(this.postParam, "warehousingUserId", res.warehousingUserId);
        this.$set(this.postParam, "warehousingUserName", res.warehousingUserName);

        this.supplierError = false;
      });
    },
    _drugDistribute(list) {
      let tableList1 = [];
      let tableList2 = [];
      let tableList3 = [];
      // 列表按类型分类
      list.forEach(item => {
        item.drugType = Number(item.drugType);
        if(item.drugType === 1) {
          tableList2.push(item);
        } else if(item.drugType === 2) {
          tableList3.push(item);
        } else if(item.drugType === 3 || item.drugType === 4) {
          tableList1.push(item);
        }
      });
      // 确定当前tab
      if(tableList1.length > 0) {
        this.activeName = '7';
        this.onDisabled(true);
      } else if(tableList2.length > 0) {
        this.activeName = '1';
        this.onDisabled(true);
      } else if(tableList3.length > 0) {
        this.activeName = '2';
        this.onDisabled(true);
      }
      // 可编辑？添加搜索框
      if(!this.readOnly) {
        tableList1.push({search: true});
        tableList2.push({search: true});
        tableList3.push({search: true});
      }
      // 初始化列表
      this.$refs.table1.setTableList(tableList1);
      this.$refs.table2.setTableList(tableList2);
      this.$refs.table3.setTableList(tableList3);
    },
    _getSuppliers() {
      getSuppliers().then(res => {
        res.content.forEach(item => {
          this.suppliers.push({
            id: item.id,
            text: item.supplierName
          });
        });
      });
    },
    _setTopHeight() {
      let topHeight = 0;
      if(this.$refs.top) {
        topHeight = this.$refs.top.clientHeight + 10;
      }
      let height = "calc(100% - " + topHeight + "px)";
      this.$set(this.tabStyle, "height", height);
    },
    _getFactors() {
      getAll().then((res) => {
        res.forEach(item => {
          this.sactors.push(item);
        });
      });
    },
    _getList() {
      // 只留当前选择的药品列表
      let type = Number(this.activeName);
      if(type == 1) {
        return this.$refs.table2.getSelectRows();
      }
      if(type == 2) {
        return this.$refs.table3.getSelectRows();
      }
      if(type == 7) {
        return this.$refs.table1.getSelectRows();
      }
      // let list1 = this.$refs.table1.getSelectRows();
      // let list2 = this.$refs.table2.getSelectRows();
      // let list3 = this.$refs.table3.getSelectRows();
      // return [
      //   ...list1,
      //   ...list2,
      //   ...list3,
      // ];
    },
  }
}
</script>

<style>
.info-form {
  height: 100%;
}

.info-form .info-form-top {
  padding-bottom: 10px;
}

.info-form .info-form-top .row:not(:first-child) {
  margin-top: 10px;
}

.info-form .info-form-tab .el-tabs {
  height: 100%;
}

.info-form .info-form-tab .error .el-input__inner, 
.info-form .info-form-tab .error .el-input__inner:focus, 
.info-form .info-form-tab .error .el-textarea__inner, 
.info-form .info-form-tab .error .el-textarea__inner:focus,
.info-form .info-form-top .error .el-input__inner,
.info-form .info-form-top .error .el-input__inner:focus  {
    border-color: #f56c6c;
}

.info-form .info-form-tab .el-tabs__item.is-disabled.is-active {
  color: #1890ff;
}
</style>